﻿using HY.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Model;
using WebApi.ViewModel;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TransporterController : BaseController
    {
        public TransporterController(ILogger<TransporterController> logger) : base(logger)
        {
        }

        /// <summary>
        /// 获取运输单位分页列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("GetPageList")]
        public async Task<ReturnModel> GetPageList(QueryTransporterListVM model)
        {
            try
            {
                Expression<Func<TransporterList, bool>> filter = e => true;
                if (!string.IsNullOrEmpty(model.Transporter))
                    filter = filter.And(c => c.transporter.Contains(model.Transporter));
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel { PageIndex = model.PageIndex, PageSize = model.PageSize };
                var data = await DbHelper.TransporterList.GetPageListAsync(filter, pageModel);
                return new ReturnModel { Count = pageModel.TotalCount, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "查询", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetPageList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(TransporterController)}/{nameof(GetPageList)}", ex);
            }
        }

        /// <summary>
        /// 获取运输单位下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("SelectList")]
        public async Task<ReturnModel> SelectList()
        {
            try
            {
                var list = await DbHelper.TransporterList.AsQueryable().Select(it => it.transporter).ToListAsync();
                return new ReturnModel { Count = list.Count, Data = list };
            }
            catch (Exception ex)
            {
                return logger.ErrorModel($"{nameof(TransporterController)}/{nameof(SelectList)}", ex);
            }
        }

        [HttpPost("Add")]
        public async Task<ReturnModel> Add(TransporterList model)
        {
            return await Save(model, true);
        }

        [HttpPost("Update")]
        public async Task<ReturnModel> Update(TransporterList model)
        {
            return await Save(model, false);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isInsert"></param>
        /// <returns></returns>
        private async Task<ReturnModel> Save(TransporterList model, bool isInsert)
        {
            try
            {
                if (DbHelper.TransporterList.IsAny(c => c.transporter == model.transporter && c.id != model.id))
                    return logger.Code_202("运输单位已存在");
                else if (isInsert)
                    await DbHelper.TransporterList.InsertAsync(model);
                else
                    await DbHelper.GetDbConn().Updateable(model).ExecuteCommandAsync();
                LogToDB("TransporterList", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("TransporterList", isInsert ? "新增" : "更新", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(Save)}-{ex.Message}");
                return logger.ErrorModel(nameof(TransporterController) + "-" + nameof(Save), ex);
            }
        }

        [HttpPost("Delete/{id}")]
        public async Task<ReturnModel> Delete(int id)
        {
            try
            {
                TransporterList model = DbHelper.TransporterList.GetById(id);
                await DbHelper.TransporterList.DeleteAsync(it => it.id == id);
                LogToDB("TransporterList", "删除", $"参数：{id},删除数据：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("TransporterList", "删除", $"参数：{id}", "异常", $"{nameof(Delete)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(TransporterController)}/{nameof(Delete)}", ex);
            }
        }
    }
}
